package com.shorturl.service.impl;


import com.shorturl.dao.UrlMapper;
import com.shorturl.pojo.Url;
import com.shorturl.service.UrlService;
import com.shorturl.uitl.Basr62Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("urlService")
public class UrlServiceImpl implements UrlService {

    @Autowired
    private UrlMapper urlMapper;


    @Override
    public String add(String url) {
        if(url == null){
            return null;
        }
        String check = urlMapper.checkUrl(url);
        if(check != null){
            return check;
        }
        Url u = new Url();
        u.setUrl(url);
        int resultCount = urlMapper.insertSelective(u);
        if(resultCount > 0){
            String sUrl = Basr62Util.encode(u.getId());
            u.setShorturl("http://localhost:8080/url/decode/"+sUrl);
            int i = urlMapper.updateByPrimaryKeySelective(u);
            if(i > 0){
                return "http://localhost:8080/url/decode/"+sUrl;
            }
        }
        return null;
    }

    @Override
    public String selecrt(String dpass) {
        if(dpass == null){
            return null;
        }
        long urlid = Basr62Util.decode(dpass);

        String url = urlMapper.selectUrlByPrimaryKey(urlid);

        if(url != null){
            return url;
        }
        return null;
    }
}
